/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
function AtomClient(uriParam) {
	
	this.msxmlNames = [ "MSXML2.XMLHTTP.5.0",
                        "MSXML2.XMLHTTP.4.0",
                        "MSXML2.XMLHTTP.3.0",
                        "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP" ];
			       
	//this.uri = uriParam.replace(":6060/","/");
	this.uri = uriParam;
	this.response=null;
	this.service = uriParam;
	this.securityToken = null;
	this.indexEntries = new Array();

	this.json = function(id, responseFunction) {
		if (id) id = '/'+id;
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.client = this;
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					if (xhr.responseText){
						var a = null;
					    try{ 
					        a = jQuery.parseJSON(xhr.responseText);
					    }catch(e){ 
					        alert(e+':'+xhr.responseText); //error in the above string(in this case,yes)! 
					    }
					    if (a) responseFunction(a,xhr.client);
					} 
				} else {
                    alert("get "+xhr.service + id+" - Error "+xhr.status+" getting JSon data from the server");
				}
			}
		};
		xhr.open("GET", this.uri + id, true);
		xhr.setRequestHeader("Pragma","no-cache");
		xhr.setRequestHeader("Cache-Control","no-cache");
		if (this.securityToken) {
			try {
				xhr.setRequestHeader ("Authorization",this.securityToken);
			} catch (e) {};
		}
		xhr.send(null);
	};

	this.jsonPost = function(id, data, responseFunction) {
		if (id) id = '/'+id;
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.client = this;
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					if (xhr.responseText){
						var a = null;
					    try{ 
					        a = jQuery.parseJSON(xhr.responseText);
					    }catch(e){ 
					        alert(e+':'+xhr.responseText); //error in the above string(in this case,yes)! 
					    }
					    if (a) responseFunction(a,xhr.client);

					} 
				} else {
                    alert("post "+xhr.service + id+" - Error "+xhr.status+" getting JSon data from the server");
				}
			}
		};
		xhr.open("POST", this.uri + id, true);
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xhr.setRequestHeader("Pragma","no-cache");
		xhr.setRequestHeader("Cache-Control","no-cache");
		if (this.securityToken) {
			xhr.setRequestHeader ("Authorization",this.securityToken);
		}
		xhr.send(data);
	};

	this.get = function(responseFunction) {
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.client = this;
		/* Specifique a Microsoft et NE FONCTIONNE PAS car XDomainRequest est maintenant a reserver a des acces a d'autres domaines SEULEMENT
		xhr.onerror = function() {
		   alert(xhr);
		}
		xhr.onload = function() {
					var aresponse = xhr.responseText;
					if (xhr.service=="pubmed") {  
						aresponse = xhr.responseText.replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
						//alert(aresponse);
					}
				    var xmlDocument = xhr.responseXML;
				    if(!xmlDocument || xmlDocument.childNodes.length==0){ 
                        xmlDocument = (new DOMParser()).parseFromString(aresponse, "text/xml");
                    } 
                    if (responseFunction != null) responseFunction(xmlDocument, aresponse,xhr.client);
		}
		*/
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				//if (xhr.status == 302) {
				//	window.location.replace(xhr.getResponseHeader("Location"));
				//} else
				if (xhr.status == 200) {
					var aresponse = xhr.responseText;
					if (xhr.service=="pubmed") {  
						aresponse = xhr.responseText.replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
						//alert(aresponse);
					}
				    var xmlDocument = xhr.responseXML;
				    if(!xmlDocument || xmlDocument.childNodes.length==0){ 
                        xmlDocument = (new DOMParser()).parseFromString(aresponse, "text/xml");
                    } 
                    if (responseFunction != null) responseFunction(xmlDocument, aresponse,xhr.client);
				} else {
                    alert("GET "+xhr.service +" -- Error "+xhr.status+" getting data from the server");
				}
			}
		};
		xhr.open("GET", this.uri, true);
		if (this.securityToken) {
			//alert(this.securityToken);
			try {
				xhr.setRequestHeader ("Authorization",this.securityToken);
			} catch (e) {};
		}
		xhr.send(null);
	};

	this.post = function (entry, responseFunction) {
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.client = this;
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 201) {
				    var aresponse = xhr.responseText;
				    var xmlDocument = xhr.responseXML;
				    if(!xmlDocument || xmlDocument.childNodes.length==0){ 
                        xmlDocument = (new DOMParser()).parseFromString(aresponse, "text/xml");
                    } 
					if (responseFunction != null) responseFunction(xmlDocument, aresponse,xhr.client);
				} else {
					alert("POST "+xhr.service +" -- Error "+xhr.status+" getting data from the server");
				}
			}
		};
		xhr.open("POST", this.uri, true);
		xhr.setRequestHeader("Content-Type", "application/atom+xml");
		if (this.securityToken) {
			try {
				xhr.setRequestHeader ("Authorization",this.securityToken);
			} catch (e) {};
		}
		xhr.send(entry);
	};

	this.put = function (id, entry, responseFunction) {
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.client = this;
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					var aresponse = xhr.responseText;
				    var xmlDocument = xhr.responseXML;
				    if(!xmlDocument || xmlDocument.childNodes.length==0){ 
                        xmlDocument = (new DOMParser()).parseFromString(aresponse, "text/xml");
                    } 
					if (responseFunction != null) responseFunction(xmlDocument, aresponse,xhr.client);
				} else {
					alert("PUT "+xhr.service+ '/' + id +" -- Error "+xhr.status+" getting data from the server");
				}
			}
		};
		xhr.open("PUT", this.uri + '/' + id, true);
		xhr.setRequestHeader("Content-Type", "application/atom+xml");
		if (this.securityToken) {
			xhr.setRequestHeader ("Authorization",this.securityToken);
		}
		xhr.send(entry);
	};

	this.del = function (id, responseFunction) {       
		var xhr = this.createXMLHttpRequest();
		xhr.service = this.service;
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					if (responseFunction != null) responseFunction();
				} else {
					alert("DELETE "+xhr.service + '/' + id+" -- Error "+xhr.status+" getting data from the server");
				}
			}
		};
		xhr.open("DELETE", this.uri + '/' + id, true);		
		if (this.securityToken) {
			try {
				xhr.setRequestHeader ("Authorization",this.securityToken);
			} catch (e) {};
		}
		xhr.send(null);
	};
	
	this.setIndexEntries = function (entries) {
		this.indexEntries = entries;
	};
	
	this.getIndexEntries = function () {
		return this.indexEntries;
	};


	this.createXMLHttpRequest = function () {
		//if (typeof XDomainRequest != "undefined"){ 
	    //    return new XDomainRequest();
		//}
        /* Mozilla XMLHttpRequest */
        try {return new XMLHttpRequest();} catch(e) {}      
		
        /* Microsoft MSXML ActiveX */
        for (var i=0;i < this.msxmlNames.length; i++) {
            try {return new ActiveXObject(this.msxmlNames[i]);} catch (e) {}
        }
        alert("XML http request not supported");
        return null;
	};

	if (typeof DOMParser == "undefined") {
	   DOMParser = function () {};
	
	   DOMParser.prototype.parseFromString = function (str, contentType) {
	      if (typeof ActiveXObject != "undefined") {
	         var d = new ActiveXObject("MSXML.DomDocument");
	         d.loadXML(str);
	         return d;
	      } else if (typeof XMLHttpRequest != "undefined") {
	         var req = new XMLHttpRequest;
	         req.open("GET", "data:" + (contentType || "application/xml") +
	                         ";charset=utf-8," + encodeURIComponent(str), false);
	         if (req.overrideMimeType) {
	            req.overrideMimeType(contentType);
	         }
	 		if (this.securityToken) {
				try {
					xhr.setRequestHeader ("Authorization",this.securityToken);
				} catch (e) {};
			}
	         req.send(null);
	         return req.responseXML;
	      }
      };
   }
}
